package com.yaorange.aspect;

import com.yaorange.annotation.PermissionAnnotation;
import com.yaorange.container.PermissionContainer;
import com.yaorange.exception.BusinessException;
import com.yaorange.response.enums.ResultCode;
import com.yaorange.utils.ThreadLocalUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Set;

/**
 *   权限切面
 */
@Component
@Aspect
public class PermissionAspect {

    @Autowired
    private PermissionContainer permissionContainer;


    @Around("@annotation(permissionAnnotation)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, PermissionAnnotation permissionAnnotation) throws Throwable{
        // 若用户是管理员，则直接放行

        // 通过本地线程获取共享数据(admin)  admin = 1
        String sysId_admin = ThreadLocalUtil.get();
        Long sysId = null;
        if(!StringUtils.hasText(sysId_admin)){
            throw new BusinessException(ResultCode.FAIL);
        }
        sysId = Long.parseLong(sysId_admin.split("-")[0]);
        // 获取注解上的权限表达式
        String value = permissionAnnotation.value();
        Set<String> containerPermission = permissionContainer.getPermission("LOGIN_USER_" + sysId);
        if(containerPermission!=null && containerPermission.contains(value)){
            Object proceed = joinPoint.proceed();
            return proceed;
        }
        throw new BusinessException(ResultCode.FORBIDDEN);
    }

}
